<?php
namespace App\Job\Prize;

use App\Query\UserQuery;
use App\Repository\UserRepository;

// 管理奖
class Manage
{
    public $users;
    
    public $money;
    
    public $config;
    
    public $config_index;
    
    public function __construct($money, $config)
    {
        // 上级用户组
        $this->users = [];
        
        $this->money = $money;
        
        $this->config = json_decode($config['manage'], true);
        
        // 当前比例，用来差值
        $this->config_index = 0;
    }
    
    // 运行
    public function run($user, $content)
    {
        // 查找用户组
        foreach(UserQuery::in(UserQuery::model(), $user->user_all)->get() as $users)
        {
            $this->users[$users->id] = $users;
        }

        // 递归用户组
        do{
            $user = $this->each($user->user_id, $content);
        }
        while($user);
    }
    
    // 递归用户组
    public function each($id, $content)
    {
        if($user = $this->users[$id] ?? null)
        {
            // 判断团队业绩
            $value = $this->money($user->money_user);

            // 奖励比例
            if($value)
            {
                // 用户
                $user = UserRepository::make($user);
                
                // 释放积分
                $money = bcmul($this->money, (float) $value / 100, 2);
                
                // 释放积分
                $user->orderMoneyRemain('manage', $money, $content);
                
                // 感恩奖，从关系链中查找
                (new Thank($money, $user->user_all))->run('【' . $user->username . '】感恩奖');
            }
            
            // 判断是否到了最大奖励
            if($this->config)
            {
                return $user;
            }
        }
    }
    
    // 检查用户团队业绩
    public function money($money)
    {
        // 符合等级比例
        $index = 0;
        
        // 循环检查等级
        foreach($this->config as $key => $value)
        {
            // 业绩达到
            if($key <= $money)
            {
                // 删除等级
                unset($this->config[$key]);
                
                // 记算差值
                $index = $value - $this->config_index;
            }
        }

        // 符合比例
        if($index > 0)
        {
            // 累加差值
            $this->config_index += $index;
        
            // 返回差值
            return $index;
        }
    }
}